package org.example.interceptor;

import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.framework.core.utils.servlet.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: api安全拦截器
 *
 * @author shenguangyang
 */
public class ApiSecurityInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(ApiSecurityInterceptor.class);
    /**
     * 拦截代码
     * 目标方法执行之前执行
     * @param request
     * @param response
     * @param arg2
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        // code和msg是从过滤器传过来的
        Object code = request.getAttribute("code");
        if ((code != null ) && ((int)code != 200)) {
            String msg = (String) request.getAttribute("msg");
            ServletUtils.writeJson(Resp.fail(msg));
            return false;
        }
        return true;
    }
}
